/**
 * NetUitl 网络请求的实现
 * @author chenliang
 * @date 2017-01-22
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {Component} from 'react';
import sign from './sign'
import {toast} from '../utils/NativeUtil'

var parseString = require('react-native-xml2js').parseString;

import {
    NativeModules
} from 'react-native';

var LoginOutPlugin = NativeModules.LoginOutPlugin;

class NetUitl extends React.Component {

    static serializeJSON(data) {
        return Object.keys(data).map(function (keyName) {
            return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
        }).join('&');
    }

    static postSign(url, data, callback) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: NetUitl.serializeJSON(sign.api(data))
        };

        fetch(url, fetchOptions)
            .then((response) => {
                if (response.status == 599) {
                    toast("您的请求过于频繁，请稍后再试");
                } else {
                    return response.text()
                }
            })
            .then((responseText) => {
                let responseJson = JSON.parse(responseText);
                if (!responseJson.success) {
                    toast(responseJson.message);
                } else {
                    callback(responseJson);
                }
            }).catch(function (e) {
            hideLoading();
        }).done();
    }


    static serializeJSON(data) {
        return Object.keys(data).map(function (keyName) {
            return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
        }).join('&');
    }

    static post(url, data, callback) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: NetUitl.serializeJSON(data)
        };

        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                let responseJson = JSON.parse(responseText);
                if (responseJson.result == "200") {
                    callback(responseJson.data);
                } else {
                    toast(responseJson.msg);
                }
            }).catch(function (e) {
            console.log(e);
        }).done();
    }

    static postNew(url, data) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: NetUitl.serializeJSON(data)
        };

        let fetchPromise = new Promise((resolve, reject) => {
            fetch(url, fetchOptions)
                .then((response) => response.text())
                .then((responseText) => {
                    console.log(responseText)
                    return JSON.parse(responseText)
                })
                
                .then((responseJson) => {
                    if (responseJson.result == "200") {
                        resolve(responseJson.data)
                    } else {
                        toast(responseJson.msg);
                        reject(responseJson.msg);
                    }
                }).catch(function (e) {
                console.log(e);
                reject('网络异常:' + e);
            }).done();
        })
        return fetchPromise;
    }

    //post请求
    /**
     *url :请求地址
     *data:参数
     *callback:回调函数
     */
    static postFrom(url, data, callback) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'data=' + data + ''//这里我参数只有一个data,大家可以还有更多的参数
        };

        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).done();
    }

    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static postJson(url, data, callback) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                //json形式
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        };

        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).done();
    }

    //get请求
    /**
     *url :请求地址
     *callback:回调函数
     */
    static  get(url, callback) {
        fetch(url)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).done();
    }

    static getNew(url) {
        let fetchPromise = new Promise((resolve, reject) => {
            fetch(url)
                .then(response => response.text())
                .then((responseText) => JSON.parse(responseText))
                .then(responseJson => {
                    if (responseJson.result == 200) {
                        resolve(responseJson.data);
                    } else {
                        reject('网络异常:' + responseJson.result);
                    }
                }).catch(function (e) {
                toast('异常:' + e);
                reject('异常:' + e);
            }).done();
        });
        return fetchPromise;
    }


}

export default NetUitl;
